package com.liruo.treasureattic.authserver.service;

import com.liruo.treasureattic.authserver.constant.MessageConstant;
import com.liruo.treasureattic.authserver.model.SecurityUser;
import com.liruo.treasureattic.common.errhandler.result.BaseResponse;
import com.liruo.treasureattic.common.model.dto.AuthUser;
import com.liruo.treasureattic.service.api.client.UserClient;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author:liruo
 * @Date:2022-10-10-14:03:01
 * @Desc
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserClient userClient;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BaseResponse<AuthUser> user = userClient.getByUsername(username);
        if(user == null || user.getCode() != 0){
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        SecurityUser securityUser = new SecurityUser(user.getData());
        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }
}
